package com.torry.edss.integration.feign.eastmoney.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import feign.Client;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.slf4j.Slf4jLogger;
import okhttp3.OkHttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import com.torry.edss.integration.feign.eastmoney.EastMoneyPush2HisFeignClient;


/**
 * @author torry.wang
 */
@Configuration
public class Push2HisFeignConfiguration {

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder().readTimeout(5, TimeUnit.MINUTES).connectTimeout(10, TimeUnit.SECONDS).build();
    }

    @Bean
    public Client skipSSLClient() {
        try {
            return Optional.of(
                    new SSLContextBuilder()
                            .loadTrustMaterial(null, (chain, authType) -> true)
                            .build()
            ).map(s ->
                    new Client.Default(
                            s.getSocketFactory(),
                            new NoopHostnameVerifier())
            ).get();
        } catch (Exception e) {
            return new Client.Default(null, null);
        }
    }

    @Bean
    public EastMoneyPush2HisFeignClient initMsApiService(Client skipSSLClient) {
        SimpleModule module = new SimpleModule();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        objectMapper.registerModule(module);
        return Feign.builder()
                .client(skipSSLClient)
                .logger(new Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder(objectMapper))
                .options(new Request.Options(5, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, true))
                .target(EastMoneyPush2HisFeignClient.class, "http://push2his.eastmoney.com");
    }
}
